package com.lee.boot.head.first.demo.intercepter;

import com.lee.boot.head.first.demo.annotation.NoInterceptor;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Auther: Lee
 * @Date: 2018/6/27 14:57
 * @Description: 拦截器是基于servlet
 */
public class LoginIntercepter implements HandlerInterceptor {

    /**
     * 进入controller方法前执行
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        if (null != o) {
            return true;
        }
        NoInterceptor noInterceptor = o.getClass().getAnnotation(NoInterceptor.class);
        if (null != noInterceptor) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) o;
        NoInterceptor methodAnnotation = handlerMethod.getMethodAnnotation(NoInterceptor.class);
        if (null != methodAnnotation) {
            return true;
        }
        String requestURI = httpServletRequest.getRequestURI();
        System.out.println(requestURI);
        if (requestURI.equals("/web/user/login") || requestURI.equals("/web/user/loginPage")) {
            return true;
        }

        Object user_info = httpServletRequest.getSession().getAttribute("_user_info");
        if (null != user_info) {
            return true;
        }
        httpServletResponse.sendRedirect("/web/user/loginPage");
        return false;
    }

    /**
     * @Description: 在controller方法执行之后，调用模板渲染界面之前执行
     * @author: Lee
     * @Date: 2019/11/23
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 完成页面渲染之后执行
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
